package com.example.demo2.service;

import com.alibaba.fastjson.JSON;
import com.example.demo2.enums.ResponseCode;
import com.example.demo2.exception.BusinessException;
import com.example.demo2.reqvo.DlpReportReqVO;
import com.example.demo2.resvo.DlpTokenResVO;
import com.example.demo2.resvo.ResponseVO;
import com.example.demo2.utils.ResponseUtils;
import com.example.demo2.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
@Slf4j
public class TestService {

    /**
     * 签名秘钥
     */
    @Value("${dlp.signature-key}")
    private String signatureKey;

    /**
     *  加密密钥
     */
    @Value("${dlp.encryption-key}")
    private String encryptionKey;

    /**
     * 请求地址
     */
    @Value("${dlp.base-url}")
    private String baseUrl;

    @Value("${dlp.client-id}")
    private String clientId;

    @Value("${dlp.secret}")
    private String secret;

    @Autowired
    private CloseableHttpClient httpClient;

    public ResponseVO<Void> acceptDeviceStatus(DlpReportReqVO dlpData) {
        log.info(" 接收dlp设备状态变化 data {}", dlpData);
        // 验签
        boolean svRes = Utils.signVerification(signatureKey, dlpData);

        if (!svRes) {
            return ResponseUtils.buildResponseVO(
                    ResponseCode.RESPONSE_RETURN_CODE_SIGN_VERIFICATION_ERROR, null);
        }

        try {
            // 解密
            String res = Utils.decryptData(encryptionKey, dlpData.getData());
            log.info(" 接收dlp设备状态上报解密结果 data {}", res);
            if (StringUtils.isEmpty(res)) {
                return ResponseUtils.buildResponseVO(ResponseCode.RESPONSE_RETURN_CODE_DECRYPT_ERROR, null);
            }
        } catch (Exception e) {
            log.error("状态上报异常：{}", e.toString());
            return ResponseUtils.buildResponseVO(ResponseCode.RESPONSE_RETURN_CODE_SUCCESS, null);
        }
        return ResponseUtils.buildResponseVO(ResponseCode.RESPONSE_RETURN_CODE_SUCCESS, null);
    }


    public ResponseVO<DlpTokenResVO> getDlpToken() {

        String url = baseUrl + "/oauth/token?grant_type=client_credentials";

        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        String originalString = clientId + ":" + secret;
        String basicToken = "Basic " + Base64.getEncoder().encodeToString(originalString.getBytes(StandardCharsets.UTF_8));;
        httpPost.addHeader("Authorization", basicToken);

        String result = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity respEntity = response.getEntity();
            result = EntityUtils.toString(respEntity, "utf-8");
            DlpTokenResVO dlpTokenResVO = JSON.parseObject(result, DlpTokenResVO.class);
            return ResponseUtils.buildResponseVO(dlpTokenResVO);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.RESPONSE_GET_TOKEN_ERROR);
        }
    }
}
